package com.shuai.user.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.text.CharSequenceUtil;
import com.shuai.common.constant.UserConstant;
import com.shuai.user.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码工具类，用户向前端发送验证码，并验证验证码
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 返回验证码给前端
     */
    @Override
    public void sendCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CircleCaptcha shearCaptcha = CaptchaUtil.createCircleCaptcha(80, 40, 4, 4);
        String captchaCookieValue = UserConstant.CAPTCHA_KEY_FOR_REDIS + UUID.randomUUID();
        response.addHeader(UserConstant.CAPTCHA_KEY_FOR_HEADER, captchaCookieValue);
        stringRedisTemplate.opsForValue().set(
                captchaCookieValue,
                shearCaptcha.getCode(),
                600L,
                TimeUnit.SECONDS);
        shearCaptcha.write(response.getOutputStream());
    }

    /**
     * 验证前端输入的验证码是否正确
     */
    @Override
    public boolean verifyCaptcha(String captchaValue, String captcha) {
        String captchaCode = stringRedisTemplate.opsForValue().get(captchaValue);
        return !CharSequenceUtil.isBlank(captchaCode) && captchaCode.equalsIgnoreCase(captcha);
    }


    public void removeCaptcha(String captchaValue) {
        stringRedisTemplate.delete(captchaValue);
    }

}
